// pages/order/order.js
var common = require("../../common/common.js").common;

var leader = require("../../common/leader.js").leader;

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        num_isShow: false,
        nav: [ {
            id: 0,
            text: "全部"
        }, {
            id: 1,
            text: "待付款"
        }, {
            id: 2,
            text: "待发货"
        }, {
            id: 3,
            text: "配送中"
        }, {
            id: 4,
            text: "待取货"
        }, {
            id: 127,
            text: "已完成"
        }, {
            id: -100,
            text: "已退款"
        }, {
            id: -126,
            text: "已售后"
        }, {
            id: -128,
            text: "已关闭"
        } ],
        choose_nav: 0,
        a: 2,
        page_sign: "order",
        cart_count: 0,
        order: [],
        search_con: "",
        code: "",
        show_code: 0,
        isIPX: "",
        page: 1,
        payBtn: false,
        showCode: 0,
        myleaderinfo: {
            leader_id: -1,
            leader_id_true: -1
        },
        goodsListStyle: {
            style: 4,
            styleConfig: {
                backgroundColor: "#fff"
            }
        },
        tabBar: [],
        tabBar1: [ {
            iconName: "icon-shouye1",
            tip: "首页",
            current: 0,
            num: 0,
            url: "/pages/index/index",
            openType: "switchTab"
        }, {
            iconName: "icon-fenlei1",
            tip: "分类",
            current: 0,
            num: 0,
            url: "/pages/classfit/classfit",
            openType: "switchTab"
        }, {
            iconName: "icon-gouwuche2",
            tip: "购物车",
            current: 0,
            num: 0,
            url: "/pages/shopcart/shopcart"
        }, {
            iconName: "icon-dingdan2",
            tip: "订单",
            current: 1,
            num: 0,
            url: "/pages/order/order",
            openType: "switchTab"
        }, {
            iconName: "icon-wode1",
            tip: "我的",
            current: 0,
            num: 0,
            url: "/pages/personal/personal",
            openType: "switchTab"
        } ],
        t_cart_num: 0
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        this.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        wx.hideTabBar();
        common.getBottomIcon(4).then(() => {
            common.getCart();
        });
        var isIPX = app.globalData.isIPX;
        this.setData({
            isIPX: isIPX
        });
        let cart_count = 0;
        let cart = wx.getStorageSync("cart") || [];
        for (var i = 0; i < cart.length; i++) {
            cart_count += cart[i]["count"];
        }
        wx.setStorage({
            key: "cart_count",
            data: cart_count
        });
        this.setData({
            cart_count: cart_count
        });
        //common.changeIconNum(cart_count,2);
        // var choose_nav = options && options.choose_nav || 0
                var choose_nav = wx.getStorageSync("order_choose_nav") || 0;
        console.log(choose_nav);
        this.setData({
            choose_nav: choose_nav
        });
        this.getBase();
        this.getData();
        leader.getMyLeaderInfo();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {
        common.getCart();
    },
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        this.setData({
            num_isShow: false
        });
        if (wx.getStorageSync("changeUidOrder")) {
            //代表，切换了城市
            this.onLoad();
            wx.removeStorage({
                key: "changeUidOrder"
            });
        }
        let cart_count = 0;
        let cart = wx.getStorageSync("cart") || [];
        for (var i = 0; i < cart.length; i++) {
            cart_count += cart[i]["count"];
        }
        wx.setStorage({
            key: "cart_count",
            data: cart_count
        });
        this.setData({
            cart_count: cart_count
        });
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        if (currentPage.__displayReporter.showReferpagepath == "pages/apply_refund/apply_refund") {
            //初始化页数，订单
            this.setData({
                page: 1,
                order: []
            });
            //从申请退款也返回，刷新数据
                        this.getData();
        }
        common.getCart();
        setTimeout(() => {
            this.setData({
                num_isShow: true
            });
        }, 1500);
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {
        this.setData({
            num_isShow: false
        });
    },
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {
        this.setData({
            num_isShow: false
        });
    },
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        common.getCart();
        this.setData({
            page: 1,
            order: []
        });
        this.getData();
        wx.stopPullDownRefresh();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {
        this.getData();
    },
    /**
   * 用户点击右上角分享
   */
    share: function(e) {
        var trade_no = e.currentTarget.dataset.trade;
        var order_id = e.currentTarget.dataset.orderid;
        wx.navigateTo({
            url: "/pages/order_confirm/order_confirm?order_no=" + trade_no + "&order_id=" + order_id + "&shai=1"
        });
    },
    goToOrderFollow(e) {
        wx.navigateTo({
            url: "/orderFollow/pages/orderFollow/orderFollow?order_id=" + e.currentTarget.dataset.orderid
        });
    },
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                var goodsListStyle = that.data.goodsListStyle;
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                that.setData({
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    leader_change: res.extra.l_change,
                    apptitle: res.extra.title,
                    style: res.extra.style,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    timeStyle: {
                        height: 32,
                        mainColor: res.extra.color_main
                    },
                    goodsListStyle: {
                        ...goodsListStyle,
                        mainColor: res.extra.color_main
                    },
                    leader_address_on: res.extra.leader_address_on,
                    t_cart_num: res.extra.cart_total_num
                });
            }
        });
    },
    choose_nav: function(e) {
        var id = e.currentTarget.dataset.id;
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        this.setData({
            choose_nav: id,
            page: 1,
            order: []
        });
        that.getData();
    },
    getData: function() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        var choose_nav = that.data.choose_nav;
        var page = that.data.page;
        common.request({
            endpoint: "My/myinfo/myorder_all2",
            method: "post",
            data: {
                openid: openid,
                status: choose_nav,
                page: page
            },
            success: res => {
                var data = that.data.order;
                //解构
                                var newData = that.orderList(res.extra);
                let order = page == 1 ? newData : data.concat(newData);
                if (res.extra.length > 0) {
                    that.setData({
                        order: order
                    });
                    that.data.page = page + 1;
                }
            }
        });
    },
    getValue: function(e) {
        var that = this;
        var search_con = e.detail.value;
        that.setData({
            search_con: search_con
        });
    },
    search: function(e) {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        var search_con = that.data.search_con;
        var choose_nav = that.data.choose_nav;
        common.request({
            endpoint: "My/myinfo/myorder_all2",
            method: "post",
            data: {
                openid: openid,
                search: search_con,
                status: choose_nav
            },
            header: {
                "content-type": "application/json"
            },
            success: res => {
                //解构
                var data = that.orderList(res.extra);
                that.setData({
                    order: data ? data : ""
                });
            },
            fail(err) {
                that.setData({
                    order: ""
                });
            }
        });
    },
    orderList(data) {
        if (data || data.length > 0) {
            data.forEach((item, index) => {
                var newProArry = [];
                var deliveryCost = [];
                var aftermarket_num = 0;
                //可售后子单数量
                                var delivery1_num = 0;
                //自提订单数量
                                var delivery2_num = 0;
                //团长配送订单数量
                                var delivery3_num = 0;
                //平台配送订单数量
                                var delivery5_num = 0;
                //骑手配送订单数量
                                var status4_num = 0;
                //待取货订单数量 
                // 拼运费字符串
                                if (item.esb_delivery && item.esb_delivery != "0.00") {
                    deliveryCost.push("平台配送费：￥" + item.esb_delivery);
                }
                if (item.express_delivery && item.express_delivery != "0.00") {
                    deliveryCost.push("快递配送费：￥" + item.express_delivery);
                }
                if (item.leader_delivery && item.leader_delivery != "0.00") {
                    deliveryCost.push("团长配送费：￥" + item.leader_delivery);
                }
                if (item.rider_fee && item.rider_fee != "0.00") {
                    deliveryCost.push("骑手配送费：￥" + item.rider_fee);
                }
                if (item.packing_fee) {
                    deliveryCost.push("包装费：￥" + parseFloat(item.packing_fee).toFixed(2));
                }
                item.pick_btn = 0;
                //确认收货按钮 平台或者快递取货
                                item.item.forEach((proInfo, proIndx) => {
                    if ((proInfo.delivery_channel == 3 || proInfo.delivery_channel == 4) && proInfo.order_status == 4) {
                        item.pick_btn = 1;
                    }
                    //统计可售后子单数量
                                        if (proInfo.aftermarket_overtime == 1) {
                        aftermarket_num++;
                    }
                    if (proInfo.order_status == "4") {
                        status4_num++;
                    }
                    switch (proInfo.delivery_channel) {
                      case "1":
                        delivery1_num++;
                        break;

                      case "2":
                        delivery2_num++;
                        break;

                      case "3":
                        delivery3_num++;
                        break;

                      case "5":
                        delivery5_num++;
                    }
                    var pro = {
                        id: proInfo.id,
                        //订单id，
                        proId: proInfo.pro_id,
                        //商品id
                        icon: proInfo.icon,
                        //商品缩略图
                        proName: proInfo.alias_name,
                        //商品名称
                        spec: proInfo.product_info,
                        //规格
                        money_refund: proInfo.money_refund,
                        //是否是满减商品
                        price: proInfo.price,
                        //商品单价
                        num: proInfo.num,
                        //数量
                        status: proInfo.status,
                        //售后状态，-1——仅退款，-2—— 退货退款，-3退货换货
                        order_status: proInfo.order_status,
                        //订单状态
                        isExpressPro: proInfo.delivery_channel == 4 ? 1 : 0,
                        //是否是快递商品，1是，2否
                        order_status: proInfo.order_status,
                        //订单状态
                        payment_channel: item.payment_channel
                    };
                    newProArry.push(pro);
                });
                var newOrder = {
                    totalNum: item.allNum,
                    item: newProArry
                };
                item.goodsListData = newOrder;
                item.deliveryCost = "(" + (deliveryCost.length > 0 ? deliveryCost.join(",") : "免配送费") + ")";
                item.aftermarket_num = aftermarket_num;
                item.delivery1_num = delivery1_num;
                item.delivery2_num = delivery2_num;
                item.delivery3_num = delivery3_num;
                item.delivery5_num = delivery5_num;
                item.status4_num = status4_num;
            });
            return data;
        }
    },
    cancel_order: common.throttle(function(e) {
        var that = this;
        var trade_no = e[0].currentTarget.dataset.ddh;
        var openid = wx.getStorageSync("user").openid;
        common.request({
            endpoint: "Order/orderinfo/cancel_order",
            method: "post",
            data: {
                trade_no: trade_no
            },
            success: res => {
                wx.reLaunch({
                    url: "/pages/order/order"
                });
            },
            fail(res) {
                wx.hideToast();
                wx.showModal({
                    title: "错误提示",
                    content: res.message,
                    showCancel: false,
                    success: function(res) {}
                });
            }
        });
    }, 5e3),
    showCode: function(e) {
        var that = this;
        var trade_no = e.currentTarget.dataset.ddh;
        var openid = wx.getStorageSync("user").openid;
        common.request({
            endpoint: "My/qrcode/getqrcode",
            method: "post",
            data: {
                openid: openid,
                trade_no: trade_no
            },
            success: res => {
                var array = wx.base64ToArrayBuffer(res.png);
                var base64 = wx.arrayBufferToBase64(array);
                that.setData({
                    code: "data:image/png;base64," + base64,
                    show_code: 1
                });
            }
        });
    },
    closeCode: function() {
        this.setData({
            show_code: 0
        });
    },
    /**
   * 生成核销码
   */
    getQrCode: function(e) {
        let that = this;
        var openid = wx.getStorageSync("user").openid;
        let order_id = e.currentTarget.dataset.orderid;
        common.request({
            endpoint: "My/qrcode/checkqrcode",
            method: "post",
            data: {
                openid: openid,
                method: 1,
                page: "pages/brand_manage/brand_manage",
                order_id: order_id
            },
            success: res => {
                that.setData({
                    code_img: res.extra,
                    showCode: 1,
                    applyCode: order_id
                });
            },
            fail(err) {
                wx.showModal({
                    title: "提示",
                    content: err.message
                });
            }
        });
    },
    closeCode: function() {
        let that = this;
        that.setData({
            showCode: 0
        });
    },
    /**
   * 立即支付
   */
    pay: function(e) {
        let that = this;
        let payment_channel = e.currentTarget.dataset.payment_channel;
        //禁用立即支付按钮
                that.setData({
            payBtn: true
        });
        var trade_no = e.currentTarget.dataset.ddh;
        var openid = wx.getStorageSync("user").openid;
        if (payment_channel == 1) {
            wx.showModal({
                title: "提示",
                content: "是否使用余额支付",
                success(res) {
                    if (res.confirm) {
                        common.request({
                            endpoint: "Order/common/sync-notify",
                            method: "post",
                            data: {
                                order_no: trade_no,
                                balance_status: 1
                            },
                            success: res => {
                                that.setData({
                                    payBtn: false
                                });
                                setTimeout(function() {
                                    wx.reLaunch({
                                        url: "/pages/order/order"
                                    });
                                }, 500);
                                wx.showToast({
                                    title: "支付成功",
                                    icon: "success"
                                });
                            },
                            fail(err) {
                                wx.showModal({
                                    title: "提示",
                                    content: err.message
                                });
                                that.setData({
                                    payBtn: false
                                });
                            }
                        });
                    } else {
                        that.setData({
                            payBtn: false
                        });
                    }
                }
            });
        } else if (payment_channel == 7) {
            wx.showModal({
                title: "提示",
                content: "是否使用专项资金支付",
                success(res) {
                    if (res.confirm) {
                        common.request({
                            endpoint: "Order/common/sync-notify",
                            method: "post",
                            data: {
                                order_no: trade_no,
                                balance_status: 2
                            },
                            success: res => {
                                that.setData({
                                    payBtn: false
                                });
                                setTimeout(function() {
                                    wx.reLaunch({
                                        url: "/pages/order/order"
                                    });
                                }, 500);
                                wx.showToast({
                                    title: "支付成功",
                                    icon: "success"
                                });
                            },
                            fail(err) {
                                wx.showModal({
                                    title: "提示",
                                    content: err.message
                                });
                                that.setData({
                                    payBtn: false
                                });
                            }
                        });
                    } else {
                        that.setData({
                            payBtn: false
                        });
                    }
                }
            });
        } else {
            common.request({
                endpoint: "order/pay",
                method: "post",
                data: {
                    openid: openid,
                    order_num: trade_no
                },
                success: res => {
                    var order_no = res.extra.order_no;
                    if (Object.prototype.toString.call(res.pay) === "[object Array]" && !res.pay.length) {
                        this.syncNotify(res.trade_no);
                    } else {
                        wx.requestPayment({
                            timeStamp: res.extra.timeStamp,
                            nonceStr: res.extra.nonceStr,
                            package: res.extra.package,
                            signType: res.extra.signType,
                            paySign: res.extra.paySign,
                            success: function(res) {
                                wx.showToast({
                                    title: "支付成功",
                                    icon: "success",
                                    mask: true,
                                    duration: 3e3,
                                    success: function(res) {
                                        wx.showToast({
                                            title: "购买成功！",
                                            icon: "success",
                                            success: function() {
                                                that.syncNotify();
                                                wx.showToast({
                                                    title: "支付成功",
                                                    icon: "success"
                                                });
                                            }
                                        });
                                    }
                                });
                            },
                            fail: function(res) {
                                wx.switchTab({
                                    url: "/pages/order/order"
                                });
                            },
                            complete: function(res) {
                                //解禁立即支付按钮
                                that.setData({
                                    payBtn: false
                                });
                            }
                        });
                    }
                },
                fail: function(res) {
                    //解禁立即支付按钮
                    that.setData({
                        payBtn: false
                    });
                    wx.showModal({
                        title: "提示",
                        content: res.message,
                        showCancel: false,
                        success(res) {
                            if (res.confirm) {
                                that.setData({
                                    page: 1
                                });
                                that.getData();
                            }
                        }
                    });
                }
            });
        }
    },
    //确认收货
    pickOrder: function(e) {
        let that = this;
        var trade = e.currentTarget.dataset.trade;
        let mchid = e.currentTarget.dataset.mchid;
        let payment_channel = e.currentTarget.dataset.payment_channel;
        wx.showModal({
            title: "提示",
            content: "是否确认收货",
            success: function(res) {
                if (res.cancel) {} else {
                    if (payment_channel == 2) {
                        if (wx.openBusinessView) {
                            wx.openBusinessView({
                                businessType: "weappOrderConfirm",
                                extraData: {
                                    merchant_id: mchid,
                                    merchant_trade_no: trade,
                                    transaction_id: ""
                                },
                                success() {
                                    //dosomething
                                },
                                fail() {
                                    //dosomething
                                },
                                complete() {
                                    common.request({
                                        endpoint: "My/myinfo/pick-order",
                                        method: "post",
                                        data: {
                                            trade_no: trade
                                        },
                                        success: res => {
                                            wx.showModal({
                                                title: "提示",
                                                content: "收货成功，您将收到货通知！",
                                                showCancel: false,
                                                success: function() {
                                                    that.setData({
                                                        page: 1,
                                                        order: []
                                                    });
                                                    that.getData();
                                                }
                                            });
                                        },
                                        fail: res => {
                                            wx.showToast({
                                                title: "确认收货失败",
                                                icon: "none"
                                            });
                                        }
                                    });
                                    //dosomething
                                                                }
                            });
                        } else {
                            common.request({
                                endpoint: "My/myinfo/pick-order",
                                method: "post",
                                data: {
                                    trade_no: trade
                                },
                                success: res => {
                                    wx.showModal({
                                        title: "提示",
                                        content: "收货成功，您将收到货通知！",
                                        showCancel: false,
                                        success: function() {
                                            that.setData({
                                                page: 1,
                                                order: []
                                            });
                                            that.getData();
                                        }
                                    });
                                },
                                fail: res => {
                                    wx.showToast({
                                        title: "确认收货失败",
                                        icon: "none"
                                    });
                                }
                            });
                            //引导用户升级微信版本
                                                }
                    } else {
                        common.request({
                            endpoint: "My/myinfo/pick-order",
                            method: "post",
                            data: {
                                trade_no: trade
                            },
                            success: res => {
                                wx.showModal({
                                    title: "提示",
                                    content: "收货成功，您将收到货通知！",
                                    showCancel: false,
                                    success: function() {
                                        that.setData({
                                            page: 1,
                                            order: []
                                        });
                                        that.getData();
                                    }
                                });
                            },
                            fail: res => {
                                wx.showToast({
                                    title: "确认收货失败",
                                    icon: "none"
                                });
                            }
                        });
                    }
                }
            }
        });
    },
    syncNotify: function() {
        common.request({
            endpoint: "Order/common/sync-notify",
            method: "post",
            data: {
                order_no: order_no
            },
            success: res => {
                setTimeout(function() {
                    wx.switchTab({
                        url: "/pages/order/order"
                    });
                }, 500);
            },
            fail(err) {
                wx.showModal({
                    title: "提示",
                    content: err.message
                });
            }
        });
    }
});